<template>
  <div style="display: flex; margin-bottom: 10px; flex-direction: row; justify-content: flex-end">
    <a-upload name="file" :action="uploadUrl" :showUploadList="false" @change="handleChange">
      <a-button style="margin-right: 5px"> 导入规则 </a-button>
    </a-upload>
    <a-button type="primary" @click="handleCreate">创建规则</a-button>
  </div>
  <div style="margin-top: 10px">
    <a-table
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      :loading="loading"
      size="middle"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'operation'">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a style="color: red" @click="handleDelete(record)">删除</a>
        </template>
      </template>
    </a-table>
    <div style="margin-top: 8px; display: flex; justify-content: space-between">
      <div style="margin-left: auto">
        <a-pagination
          :current="currentPage"
          :page-size="pageSize"
          :total="total"
          :show-total="(total) => `总数 ${total}`"
          responsive
          show-size-changer
          show-less-items
          @change="onPageChange"
          @show-size-change="onShowSizeChange"
        />
      </div>
    </div>
  </div>

  <div v-if="showCreate">
    <ReportCreateModal :visible="showCreate" @ok="onCreateOk" @cancel="onCreateCancel" />
  </div>

  <div v-if="showEdit">
    <ReportEditModal
      :visible="showEdit"
      :rule-data="editData"
      @ok="onEditOk"
      @cancel="onEditCancel"
    />
  </div>

  <div v-if="showDelete">
    <DeleteModal
      :visible="showDelete"
      title="删除上报规则"
      :data="deleteData"
      @ok="onDeleteOk"
      @cancel="onDeleteCancel"
    />
  </div>
</template>

<script>
  import { Table, message, Divider, Pagination, Upload } from 'ant-design-vue'
  import DeleteModal from '../components/DeleteModal.vue'
  import {
    createReportRule,
    getReportRuleList,
    deleteReportRule,
    editReportRule,
  } from '/@/api/module/reportRule'
  import { useRouter } from 'vue-router'
  import { useModuleStoreWithOut } from '/@/store/modules/module'
  import ReportCreateModal from './ReportCreateModal.vue'
  import ReportEditModal from './ReportEditModal.vue'

  export default {
    components: {
      'a-table': Table,
      'a-pagination': Pagination,
      'a-divider': Divider,
      'a-upload': Upload,
      DeleteModal,
      ReportCreateModal,
      ReportEditModal,
    },
    data() {
      return {
        uploadUrl: '',
        router: useRouter(),
        store: useModuleStoreWithOut(),
        showDelete: false,
        showCreate: false,
        showEdit: false,
        editData: null,
        deleteData: null,
        loading: false,
        tableData: [],
        totalData: [],
        currentPage: 1,
        pageSize: 10,
        total: 10,
        columns: [
          {
            title: 'ID',
            key: 'ruleId',
            dataIndex: 'ruleId',
            align: 'center',
          },
          {
            title: 'Description',
            key: 'desc',
            dataIndex: 'desc',
            align: 'center',
          },
          {
            title: 'Match Type',
            key: 'matchType',
            dataIndex: 'matchType',
            align: 'center',
          },
          {
            title: 'Match Rule',
            key: 'matchRule',
            dataIndex: 'matchRule',
            align: 'center',
          },
          {
            title: 'Parent',
            key: 'parentName',
            dataIndex: 'parentName',
            align: 'center',
          },
          {
            title: 'Create Time',
            key: 'createTime',
            dataIndex: 'createTime',
            align: 'center',
          },
          {
            title: 'Operation',
            key: 'operation',
            dataIndex: 'operation',
            align: 'center',
            fixed: 'right',
            width: 120,
          },
        ],
      }
    },
    async mounted() {
      this.uploadUrl =
        import.meta.env.VITE_GLOB_API_URL + '/report_rule/import?module=' + this.store.getParent.id
      await this.refreshTable()
    },
    methods: {
      async refreshTable() {
        this.loading = true
        this.totalData = await getReportRuleList({ module: this.store.getParent.id })
        this.total = this.totalData && this.totalData.length
        this.updateTableData()
        this.loading = false
      },
      updateTableData() {
        if (this.totalData != null) {
          const start = (this.currentPage - 1) * this.pageSize
          const end = start + this.pageSize
          this.tableData = this.totalData.slice(start, end)
        } else {
          this.tableData = []
        }
      },
      handleCreate() {
        this.showCreate = true
      },
      onCreateOk(data) {
        this.showCreate = false
        createReportRule({
          moduleId: this.store.getParent.id,
          desc: data.desc,
          parent: data.parent,
          matchType: data.matchType,
          matchRule: data.matchRule,
        })
          .then(async () => {
            message.success('create report rule success')
            this.refreshTable()
          })
          .catch((e) => {
            console.error('create report rule failed', e)
            message.error('create report rule failed')
          })
      },
      onCreateCancel() {
        this.showCreate = false
      },
      handleEdit(record) {
        this.editData = record
        this.showEdit = true
      },
      onEditOk(data) {
        this.showEdit = false
        editReportRule({
          ruleId: data.ruleId,
          desc: data.desc,
          matchType: data.matchType,
          matchRule: data.matchRule,
          parent: data.parentName,
        })
          .then(async () => {
            message.success('edit report rule success')
            this.refreshTable()
          })
          .catch((e) => {
            console.error('edit report rule failed', e)
            message.error('edit report rule failed')
          })
      },
      onEditCancel() {
        this.showEdit = false
      },
      handleDelete(record) {
        this.deleteData = {
          ruleId: record.ruleId,
          name: record.desc,
        }
        this.showDelete = true
      },
      onDeleteOk(data) {
        this.showDelete = false
        deleteReportRule({
          ruleId: data.ruleId,
        })
          .then(async () => {
            this.refreshTable()
            message.success('delete report rule success')
          })
          .catch((e) => {
            console.error('delete report rule failed', e)
            message.error('delete report rule failed')
          })
      },
      onDeleteCancel() {
        this.showDelete = false
      },
      async onShowSizeChange(current, size) {
        this.pageSize = size
        this.currentPage = 1
        this.updateTableData()
      },
      onPageChange(page) {
        this.currentPage = page
        this.updateTableData()
      },
      onSelectChange(selectedRowKeys) {
        this.rowSelection.selectedRowKeys = selectedRowKeys
      },
      handleChange(info) {
        console.log('handleChange:', info)
        if (info.file.status === 'uploading') {
          this.loading = true
        } else if (info.file.status === 'done') {
          this.loading = false
          this.refreshTable()
          message.success('import success')
        } else {
          message.error('import failed')
          this.loading = false
        }
      },
    },
  }
</script>
